
package com.xtsoft.platform.base.system.service.impl;


import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.repository.Sort;
import com.xtsoft.core.service.impl.GenericServiceImpl;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.platform.base.system.domain.*;
import com.xtsoft.platform.base.system.repository.*;
import com.xtsoft.platform.base.system.service.SysRoleService;
import com.xtsoft.platform.globe.Constants.Constants;
import com.xtsoft.platform.globe.enums.ResourceType;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service("sysRoleService")
public class SysRoleServiceImpl extends GenericServiceImpl<SysRole, String, SysRoleRepository>
		implements SysRoleService {

	@Autowired
	private SysRoleRepository sysRoleRepository;
	@Autowired
	private SysResourceRepository sysResourceRepository;
	@Autowired
	private SysUserRepository sysUserRepository;
	@Autowired
	private UserRoleRepository userRoleRepository;
	@Autowired
	private ResourceRoleRepository resourceRoleRepository;
	@Autowired
	private SysDashboardRepository sysDashboardRepository;
	@Autowired
	private DashboardRoleRepository dashboardRoleRepository;

	/**
	 * 获取角色树
	 */
	@Override
	public String getRoleTree(String userId) throws ParseException {
		SysUser curUser = (SysUser) SecurityUtils.getLoginedUser();
		List<SysRole> roleList;
		if (curUser.getLoginId().equals(Constants.AdminLoginId)) {
			roleList = sysRoleRepository.findAll();
		} else {
			QueryFilter filter = new QueryFilter(SysRole.class);
			filter.addFilter("Q_alias_S_NEQ", Constants.AdminRole);
			filter.addSort("roleLevel", Sort.ASC);
			QueryResult<SysRole> result = this.anyQuery(filter);
			roleList = result.getResultList();
		}

		StringBuffer jsonTreeBuffer = new StringBuffer("[");
		String jsonTree = "";
		Optional<SysUser> user = sysUserRepository.findById(userId);
		if (user.isPresent()) {
			List<UserRole> userRoles = userRoleRepository.findBySysUser(user.get());
			List<SysRole> sysRoles = userRoles.stream().map(mapper->mapper.getSysRole()).distinct().collect(Collectors.toList());
			boolean check = false;
			// 循环ROlE和USER,当USER存在ROLE CHECK为TRUE //？多级授权后期是否 按阶级角色进行过滤
			for (SysRole sysRole : roleList) {
				if (sysRoles.contains(sysRole)) {
					check = true;
				}
				jsonTreeBuffer.append("{\"id\":\"" + sysRole.getRoleId() + "\",\"text\":\"" + sysRole.getRoleName()
						+ "\",\"iconCls\":\"x-fa fa-user-md\",\"checked\":" + check
						+ ",\"leaf\":true,\"children\":[]},");
				check = false;
			}
			jsonTree = jsonTreeBuffer.substring(0, jsonTreeBuffer.length() - 1) + "]";
		}
		return jsonTree;
	}

	/**
	 * 角色授权
	 */
	@Override
	@Transactional
	public String impower(String roleId, String resourceId,String ids) {
		Optional<SysRole> sysRole = sysRoleRepository.findById(roleId);
		String array[] = ids.split(",");
		List<String> resourceIds = Arrays.asList(array);
		List<ResourceRole> resourceRoles = new ArrayList();
		if (sysRole.isPresent()) {
			//移除所有菜单资源 当页的按钮资源
			List<ResourceRole> rrs = sysRole.get().getResourceRoles();
			List<SysResource> list = new ArrayList<>();
			for (ResourceRole resourceRole : rrs) {
				list.add(resourceRole.getSysResource());
			}
			Iterator<SysResource> sysResourcetcutIter = list.iterator();
			while (sysResourcetcutIter.hasNext()) {
				SysResource sysResource = sysResourcetcutIter.next();
				if(sysResource.getResourceType()== ResourceType.ViewMenu.getIntValue()||sysResource.getResourceType()==ResourceType.Other.getIntValue()||sysResource.getResourceType()==1|| sysResource.getPreResourceId().equals(resourceId)){
					sysResourcetcutIter.remove();
					String rui = sysResource.getResUniqueId();
					String rid = sysRole.get().getRoleId();
					resourceRoleRepository.deleteByResUniqueIdAndRoleId(rui,rid);
				}
			}
			// 添加授权的资源
		    List<SysResource> resources = sysResourceRepository.findByResUniqueIdIn(resourceIds);
		    for (SysResource sysResource : resources) {
		    	ResourceRole resourceRole = new ResourceRole();
		    	resourceRole.setSysResource(sysResource);
		    	resourceRole.setSysRole(sysRole.get());
		    	resourceRoles.add(resourceRole);
			}
		    resourceRoleRepository.saveAll(resourceRoles);
		    return "{succees:true}";
		}
		return "{succees:false}";
	}
	
	/**
	 * 删除角色
	 */
	@Transactional
	@Override
	public void deleteByRoleId(String id) {
		// TODO Auto-generated method stub
		userRoleRepository.deleteByRoleId(id);
		resourceRoleRepository.deleteByRoleId(id);
		this.remove(id);
	}

	@Override
	public List<SysRole> findByAliasAndState(String alias, int state) {
		// TODO Auto-generated method stub
		return sysRoleRepository.findByAliasAndState(alias, state);
	}

	@Override
	@Transactional
	public ResultMsg configDashBoard(String ids, String roleId) {
		// TODO Auto-generated method stub
		String[] arrId=ids.split(",");
		SysRole sysRole = sysRoleRepository.findById(roleId).get();//.findongetOne(roleId);
		if(null==sysRole)
			return new ResultMsg(false,"未知的对象分配");
		//删除原有的角色, 这是OneToMany关系正确的写法，注意OneToMany的配置
		dashboardRoleRepository.deleteBySysRole(sysRole);
		//dashboardRoleRepository.flush();
		List<SysDashboard> dashboards = sysDashboardRepository.findByDashboardIdIn(Arrays.asList(arrId));
		List<DashboardRole> dashboardRoles = new ArrayList();
		//获取勾选的角色对象并将其插入user对象中
		for (SysDashboard dashboard : dashboards) {
			DashboardRole dashboardRole = new DashboardRole();
			dashboardRole.setSysDashboard(dashboard);
			dashboardRole.setSysRole(sysRole);
			dashboardRoles.add(dashboardRole);
			/*
			if(!dashboardId.equals("root")) {
				SysDashboard sysDashboard = sysDashboardRepository.getOne(dashboardId);
				DashboardRole dashboardRole = new DashboardRole();
				dashboardRole.setSysDashboard(sysDashboard);
				dashboardRole.setSysRole(sysRole);
				sysRole.getDashboardRoles().add(dashboardRole);
			}
			*/
		}
		dashboardRoleRepository.saveAll(dashboardRoles);
		//sysRoleRepository.save(sysRole);
		return new ResultMsg(true,"分配成功");
	}
}